<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-07-26
 * Time: 14:17
 */

namespace App\Services;

use App\Traits\FilterParameters;
use App\Repositories\PermissionRepository;
use App\Repositories\RoleRepository;
use App\Repositories\UserRepository;
use App\Services\Admin\PermissionService;
use Illuminate\Support\Facades\Log;

/**
 * 遵循SOLID原则（分割、单元测试、mock测试）
 * 涉及到user的外部行为逻辑:例如统计、计算、邮件、调用外部接口等
 * 该逻辑将注入到 @class UserController
 * Class UserService
 * @package App\Services
 */
class UserService extends BaseAdminService
{
    use FilterParameters;

    /**
     * @var UserRepository 注入的UserRepository
     */
    private $userRepository;

    /**
     * @var PermissionRepository 注入的PermissionRepository
     */
    protected $permissionRepository;

    /**
     * @var RoleRepository 注入的RoleRepository
     */
    protected $roleRepository;

    /**
     * UserService constructor.
     * @param UserRepository $userRepository
     */
    public function __construct(UserRepository $userRepository,
                                PermissionRepository $permissionRepository,
                                RoleRepository $roleRepository){
        $this->userRepository = $userRepository;
        $this->permissionRepository = $permissionRepository;
        $this->roleRepository = $roleRepository;
    }

    /**
     * 返回用户列表
     * @param array $data
     * @return mixed
     */
    public function getUserPage(array $data){

        //处理参数
        $limit = data_get($data, 'limit', LIMIT_PAGE);
        $arrData = $this->handleFilterUserCondition($data);

        $realStatue = data_get($data, 'real_status', null);

        return $this->userRepository->getUserPage($arrData, $realStatue, $limit);
    }

    /**
     * 软删除管理员
     * @param $id
     * @return int
     */
    public function deleteManageUser($id){
        return $this->userRepository->deleteManageUser($id);
    }

    /**
     * 获取管理员列表
     * @param array $data
     * @return mixed
     */
    public function getManageUserPage(array $data){

        //处理参数
        $limit = data_get($data, 'limit', LIMIT_PAGE);
        $arrData = $this->handleFilterUserCondition($data);

        return $this->userRepository->getManageUserPage($arrData, $limit);
    }

    /**
     * 获取某条管理员数据
     * @param int $id
     * @return mixed
     */
    public function getManagerSingle(int $id){
        return $this->userRepository->getManagerSingle($id);
    }

    /**
     * 编辑管理员 将角色授权给用户
     * @param array $data
     * @return array
     */
    public function updateManageUser(array $data){

        $roleIds = data_get($data, 'role_ids');
        $user = $this->userRepository->updateManageUser($data);

        return $this->roleToUser($roleIds, $user);
    }

    /**
     * 新增管理员 将角色授权给用户
     * @param array $data
     * @return array
     */
    public function addManageUser(array $data){

        $roleIds = data_get($data, 'role_ids');
        $user = $this->userRepository->addManageUser($data);

        return $this->roleToUser($roleIds, $user);
    }

    /**
     * 将角色授权给用户 支持多个角色
     * 直接覆盖现有角色
     * 没有角色时表示删除所有角色
     * @param array $roleIds
     * @param array $user
     * @return array
     */
    protected function roleToUser(array $roleIds, array $user){
        if($user['user_type'] = SUPER_ADMIN){

            //处理超级管理员
            $roles = $this->roleRepository->getAllRoleListByCondition(['name'=>'super-admin']);
        }else{

            //无授权的权限
            $this->notRoleToUser($roleIds, $user);

            //根据IDS查看所有的权限
            $roles = $this->roleRepository->getAllRoleListByIds($roleIds);
        }

        if ($roles->IsEmpty()) {
            return $this->returnServerData(false, '参数错误，无法找到角色');
        }

        try {

            //将多个角色授权给用户 会将以前的角色删除
            $user->syncRoles($roles);

            return $this->returnServerData(true, '', $user);

        } catch (\Exception $exception) {
            return $this->returnServerData(false, '无法授权给用户，请联系管理员');
        }
    }

    /**
     * 无授权的权限
     * @param array $roleIds
     * @param $user
     * @return array
     */
    protected function notRoleToUser(array $roleIds, $user){

        //如果没有角色 则将当前用户所有的角色删除
        if (!$roleIds) {
            $roles = $user->getRoleNames;
            $roles->map(function ($role) use ($user) {
                $user->removeRole($role);
            });

            return $this->returnServerData(true, '', $user);
        }
    }

    /**
     * 获取用户实名认证信息
     * @param int $userId
     * @return mixed
     */
    public function getUserAuthentication(int $userId){
        return $this->userRepository->getUserAuthentication($userId);
    }
}
